const express = require('express');
const router = express.Router();
const multer = require('multer');
const db = require('../models');
const sequelize = db.sequelize;
const authMiddleware = require('../middlewares/authMiddleware');

// 配置文件上传
const upload = multer({
  dest: 'uploads/temp/',
  limits: {
    fileSize: 10 * 1024 * 1024 // 10MB
  }
});

// 导入各个路由模块
const authRoutes = require('./auth.routes');
const whatsappRoutes = require('./whatsapp.routes');
const messageRoutes = require('./message.routes');
const contactRoutes = require('./contact.routes');
const presetRoutes = require('./preset.routes');
const reportRoutes = require('./report.routes');
const settingsRoutes = require('./settings.routes');
const userRoutes = require('./userRoutes');
const crmRoutes = require('./crmRoutes');
const presetFilesRoutes = require('./presetFilesRoutes');

// CRM相关控制器，直接导入用于路由别名
const contactController = require('../controllers/contactController');
const authController = require('../controllers/authController');
const presetFileController = require('../controllers/presetFileController');
const { authenticate, isAdmin } = require('../middlewares/authMiddleware');
const reportController = require('../controllers/reportController');
const settingsController = require('../controllers/settingsController');

// 导入活跃度路由
const activityRoutes = require('./activityRoutes');

// 使用路由
router.use('/auth', authRoutes);
router.use('/whatsapp', whatsappRoutes);
router.use('/messages', messageRoutes);
router.use('/contacts', contactRoutes);
router.use('/presets', presetRoutes);
router.use('/reports', reportRoutes);
router.use('/settings', settingsRoutes);

// 添加CRM路由别名
router.get('/crm/customers', authenticate, contactController.getAllCrmCustomers);
router.get('/crm/customers/export', authenticate, contactController.exportCrmData);
router.put('/crm/customers/:id', authenticate, contactController.updateCrmInfo);
router.post('/crm/customers', authenticate, contactController.addCrmCustomer);
router.delete('/crm/customers/:id', authenticate, contactController.deleteCrmCustomer);

// 添加详细的CRM路由调试日志
router.get('/contacts/crm/customers', authenticate, (req, res, next) => {
  console.log('---------- CRM客户列表请求 ----------');
  console.log('请求路径:', req.path);
  console.log('请求方法:', req.method);
  console.log('查询参数:', req.query);
  console.log('授权头:', req.headers.authorization ? '有效' : '无效');
  console.log('用户信息:', req.user ? `ID: ${req.user.id}, 角色: ${req.user.role}` : '未授权');
  
  // 记录当前时间戳，用于计算处理时间
  req.requestTime = Date.now();
  
  try {
    // 提供临时CRM客户数据
    console.log('提供临时CRM客户数据');
    
    // 解析分页参数
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    
    // 模拟客户数据
    const mockCustomers = [
      {
        id: 1,
        name: '张三企业科技',
        contactId: null,
        status: 'lead',
        product: '企业WhatsApp服务',
        quantity: '1年服务',
        location: '北京',
        notes: '对企业级服务有兴趣',
        source: '网站',
        industry: '科技',
        createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
        phone: '13800138001',
        contact: null,
        rating: 3
      },
      {
        id: 2,
        name: '李四贸易有限公司',
        contactId: null,
        status: 'customer',
        product: '高级订阅',
        quantity: '50用户',
        location: '上海',
        notes: '已完成签约',
        source: '销售推荐',
        industry: '贸易',
        createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
        phone: '13900139001',
        contact: null,
        rating: 5
      },
      {
        id: 3,
        name: '王五医疗器械',
        contactId: null,
        status: 'prospect',
        product: '标准服务',
        quantity: '试用期',
        location: '广州',
        notes: '正在评估方案',
        source: '展会',
        industry: '医疗',
        createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
        phone: '13700137001',
        contact: null,
        rating: 4
      }
    ];
    
    // 模拟统计数据
    const mockStats = {
      total: 3,
      leads: 1,
      prospects: 1,
      customers: 1,
      inactive: 0
    };
    
    // 使用自定义响应拦截记录响应信息
    const originalJson = res.json;
    res.json = function(data) {
      console.log('CRM响应时间:', Date.now() - req.requestTime, 'ms');
      console.log('CRM响应状态:', res.statusCode);
      console.log('CRM响应数据:', data ? '数据长度: ' + JSON.stringify(data).length : '无数据');
      return originalJson.call(this, data);
    };
    
    res.json({
      data: mockCustomers,
      total: mockCustomers.length,
      stats: mockStats,
      page,
      pageSize
    });
  } catch (err) {
    console.error('CRM路由处理临时数据失败:', err);
    next(err);
  }
});

// 添加一个错误处理中间件专门处理CRM路由
router.use('/contacts/crm', (err, req, res, next) => {
  console.error('CRM路由错误:', err);
  console.error('错误堆栈:', err.stack);
  
  // 如果是Sequelize错误，记录更多信息
  if (err.name === 'SequelizeError' || err.name === 'SequelizeDatabaseError') {
    console.error('SQL错误:', err.sql);
    console.error('SQL错误参数:', err.parameters);
  }
  
  // 发送错误响应
  res.status(500).json({
    message: '处理CRM请求时出错',
    error: err.message,
    type: err.name,
    time: new Date().toISOString()
  });
});

// 其他已有的CRM路由也使用临时处理
// 导出功能 - 临时处理
router.get('/contacts/crm/customers/export', authenticate, (req, res) => {
  console.log('临时处理CRM客户数据导出请求');
  
  // 模拟客户数据
  const mockCustomers = [
    {
      id: 1,
      name: '张三企业科技',
      phone: '13800138001',
      product: '企业WhatsApp服务',
      quantity: '1年服务',
      location: '北京',
      notes: '对企业级服务有兴趣',
      createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
      updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000)
    },
    {
      id: 2,
      name: '李四贸易有限公司',
      phone: '13900139001',
      product: '高级订阅',
      quantity: '50用户',
      location: '上海',
      notes: '已完成签约',
      createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
      updatedAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000)
    },
    {
      id: 3,
      name: '王五医疗器械',
      phone: '13700137001',
      product: '标准服务',
      quantity: '试用期',
      location: '广州',
      notes: '正在评估方案',
      createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
      updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000)
    }
  ];
  
  // 构建CSV头
  const csvHeader = 'ID,姓名,电话,产品,数量,地区,备注,创建时间,更新时间\n';
  
  // 构建CSV内容
  const csvContent = mockCustomers.map(customer => {
    return `${customer.id},"${customer.name}","${customer.phone || ''}","${customer.product || ''}","${customer.quantity || ''}","${customer.location || ''}","${customer.notes || ''}","${customer.createdAt}","${customer.updatedAt}"`;
  }).join('\n');
  
  // 设置响应头
  res.setHeader('Content-Type', 'text/csv');
  res.setHeader('Content-Disposition', 'attachment; filename=crm-customers.csv');
  
  // 发送CSV数据
  res.send(csvHeader + csvContent);
});

// 更新客户 - 临时处理
router.put('/contacts/crm/customers/:id', authenticate, (req, res) => {
  const { id } = req.params;
  const crmData = req.body;
  console.log(`临时处理更新客户请求，ID: ${id}`, crmData);
  res.json({ 
    message: '客户信息已更新', 
    success: true,
    customer: {
      id: parseInt(id),
      ...crmData,
      updatedAt: new Date()
    }
  });
});

// 添加客户 - 临时处理
router.post('/contacts/crm/customers', authenticate, (req, res) => {
  const crmData = req.body;
  console.log(`临时处理添加客户请求:`, crmData);
  const newId = Date.now() % 1000;
  res.status(201).json({
    message: '已添加到CRM系统',
    id: newId,
    name: crmData.name,
    created: true,
    success: true
  });
});

// 删除客户 - 临时处理
router.delete('/contacts/crm/customers/:id', authenticate, (req, res) => {
  const { id } = req.params;
  console.log(`临时处理删除客户请求，ID: ${id}`);
  res.json({
    success: true,
    message: 'CRM客户已删除'
  });
});

// 评分更新 - 临时处理
router.put('/contacts/crm/customers/:id/rating', authenticate, (req, res) => {
  const { id } = req.params;
  const { rating } = req.body;
  console.log(`临时处理客户评分更新，ID: ${id}, 评分: ${rating}`);
  res.json({
    success: true,
    message: '客户评分已更新',
    rating: parseInt(rating)
  });
});

// 批量删除 - 临时处理
router.delete('/contacts/crm/customers/batch', authenticate, (req, res) => {
  const { ids } = req.body;
  console.log(`临时处理批量删除客户请求，IDs: ${ids.join(', ')}`);
  res.json({
    success: true,
    message: `成功删除${ids.length}个客户`,
    count: ids.length
  });
});

// 添加联系人路由别名
router.get('/contacts/recent', authenticate, contactController.getRecentContacts);
router.get('/contacts/search', authenticate, contactController.searchContacts);

// 添加管理员路由
// 解决路由冲突，使用一个路由处理不同的查询条件
router.get('/admin/users', authenticate, isAdmin, (req, res, next) => {
  try {
    const { role } = req.query;
    if (role === 'sales') {
      return authController.getSalesUsers(req, res, next);
    }
    return authController.getAllUsers(req, res, next);
  } catch (error) {
    console.error('获取用户列表出错:', error);
    return res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
});

router.post('/admin/users', authenticate, isAdmin, authController.register);
router.put('/admin/users/:id', authenticate, isAdmin, authController.updateUserStatus);
router.patch('/admin/users/:id', authenticate, isAdmin, authController.updateUser);

// 实现真正的用户删除功能
router.delete('/admin/users/:id', authenticate, isAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    console.log(`尝试删除用户ID: ${id}, 请求来自管理员ID: ${req.user.id}`);
    console.log(`请求头:`, req.headers);
    
    // 防止删除当前登录用户
    if (id == req.user.id) {
      console.log('拒绝删除：用户尝试删除自己');
      return res.status(400).json({ message: '不能删除当前登录的用户' });
    }
    
    // 导入所有需要的模型
    const { 
      User, 
      WhatsappSession, 
      Message, 
      ActivityLog, 
      PresetFile, 
      CrmCustomer,
      sequelize 
    } = require('../models');
    
    // 查找用户
    const user = await User.findByPk(id);
    
    if (!user) {
      console.log(`用户ID ${id} 不存在`);
      return res.status(404).json({ message: '用户不存在' });
    }
    
    console.log(`找到用户: ${user.username}, 角色: ${user.role}`);
    
    // 防止删除管理员
    if (user.role === 'admin') {
      console.log('拒绝删除：目标用户是管理员');
      return res.status(400).json({ message: '不能删除管理员账号' });
    }
    
    // 删除相关联的数据，以避免外键约束错误
    console.log(`开始清理用户关联数据...`);
    
    try {
      // 使用事务确保数据一致性
      await sequelize.transaction(async (t) => {
        // 删除WhatsApp会话（如果表存在）
        try {
          if (WhatsappSession) {
            const deletedSessions = await WhatsappSession.destroy({
              where: { userId: id },
              transaction: t
            });
            console.log(`删除了 ${deletedSessions} 个WhatsApp会话`);
          }
        } catch (sessionError) {
          console.log('WhatsApp会话清理跳过:', sessionError.message);
        }
        
        // 删除活动日志（如果表存在）
        try {
          if (ActivityLog) {
            const deletedLogs = await ActivityLog.destroy({
              where: { userId: id },
              transaction: t
            });
            console.log(`删除了 ${deletedLogs} 个活动日志`);
          }
        } catch (logError) {
          console.log('活动日志清理跳过:', logError.message);
        }
        
        // 消息处理（如果表存在）
        try {
          if (Message) {
            const deletedMessages = await Message.destroy({
              where: { userId: id },
              transaction: t
            });
            console.log(`删除了 ${deletedMessages} 条消息`);
          }
        } catch (messageError) {
          console.log('消息清理跳过:', messageError.message);
        }
        
        // 预设文件处理（如果表存在）
        try {
          if (PresetFile) {
            const updatedFiles = await PresetFile.update(
              { createdBy: null },
              { where: { createdBy: id }, transaction: t }
            );
            console.log(`更新了 ${updatedFiles[0]} 个预设文件的创建者`);
          }
        } catch (fileError) {
          console.log('预设文件清理跳过:', fileError.message);
        }
        
        // CRM客户处理（如果表存在）
        try {
          if (CrmCustomer) {
            const updatedCustomers = await CrmCustomer.update(
              { createdBy: null },
              { where: { createdBy: id }, transaction: t }
            );
            console.log(`更新了 ${updatedCustomers[0]} 个CRM客户的创建者`);
          }
        } catch (crmError) {
          console.log('CRM客户清理跳过:', crmError.message);
        }
        
        // 删除用户本身
        await user.destroy({ transaction: t });
        console.log(`用户删除成功`);
      });
    } catch (error) {
      console.error('事务执行失败:', error);
      return res.status(500).json({ 
        message: '删除用户关联数据失败',
        error: error.message
      });
    }
    
    // 验证用户是否确实被删除
    const checkAfterDelete = await User.findByPk(id);
    if (checkAfterDelete) {
      console.error(`错误: 用户 ${id} 删除操作完成但仍然存在`);
      return res.status(500).json({ message: '用户删除操作未成功完成' });
    }
    
    console.log(`用户 ${user.username} (ID: ${id}) 已成功删除`);
    return res.status(200).json({ 
      message: '用户删除成功',
      deletedUser: {
        id: Number(id),
        username: user.username
      }
    });
  } catch (error) {
    console.error('删除用户出错:', error);
    return res.status(500).json({ 
      message: '服务器内部错误', 
      error: error.message,
      stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
    });
  }
});

// 添加预设文件路由别名
router.get('/admin/preset-files', authenticate, isAdmin, presetFileController.getAllPresetFiles);
router.post('/admin/preset-files', authenticate, isAdmin, upload.single('file'), presetFileController.uploadPresetFile);
router.get('/admin/preset-files/:id', authenticate, isAdmin, presetFileController.getPresetFile);
router.get('/admin/preset-files/:id/download', authenticate, isAdmin, presetFileController.downloadPresetFile);
router.delete('/admin/preset-files/:id', authenticate, isAdmin, presetFileController.deletePresetFile);

// 添加报告路由别名
router.get('/admin/reports/activity', authenticate, isAdmin, reportController.getActivityReport);
router.get('/admin/reports/messages', authenticate, isAdmin, reportController.getMessageStats);
router.get('/admin/reports/dashboard/stats', authenticate, isAdmin, reportController.getDashboardStats);
router.get('/reports/user-dashboard', authenticate, reportController.getUserDashboardStats);

// 添加黑名单设置路由别名
// 临时禁用认证，仅用于开发测试
router.get('/admin/settings/blacklist', settingsController.getBlacklist);
router.post('/admin/settings/blacklist', settingsController.addBlacklistItem);
router.delete('/admin/settings/blacklist/phone/:id', settingsController.deletePhoneBlacklistItem);
router.delete('/admin/settings/blacklist/content/:id', settingsController.deleteContentBlacklistItem);

// 添加仪表盘统计数据API路由别名
// 临时禁用认证，仅用于开发测试
router.get('/reports/dashboard/stats', reportController.getDashboardStats);

// 添加一个不需要认证的仪表盘数据路由(仅开发环境使用)
router.get('/reports/dashboard/demo-stats', reportController.getDashboardStats);

// 临时API，返回模拟的CRM客户数据
router.get('/crm/customers/temp', (req, res) => {
  try {
    console.log('提供临时CRM客户数据');
    
    // 模拟客户数据
    const mockCustomers = [
      {
        id: 1,
        name: '张三企业科技',
        contactId: null,
        status: 'lead',
        product: '企业WhatsApp服务',
        quantity: '1年服务',
        location: '北京',
        notes: '对企业级服务有兴趣',
        source: '网站',
        industry: '科技',
        createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
        phone: '13800138001',
        contact: null,
        rating: 3
      },
      {
        id: 2,
        name: '李四贸易有限公司',
        contactId: null,
        status: 'customer',
        product: '高级订阅',
        quantity: '50用户',
        location: '上海',
        notes: '已完成签约',
        source: '销售推荐',
        industry: '贸易',
        createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
        phone: '13900139001',
        contact: null,
        rating: 5
      },
      {
        id: 3,
        name: '王五医疗器械',
        contactId: null,
        status: 'prospect',
        product: '标准服务',
        quantity: '试用期',
        location: '广州',
        notes: '正在评估方案',
        source: '展会',
        industry: '医疗',
        createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
        updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
        phone: '13700137001',
        contact: null,
        rating: 4
      }
    ];
    
    // 模拟统计数据
    const mockStats = {
      total: 3,
      leads: 1,
      prospects: 1,
      customers: 1,
      inactive: 0
    };
    
    // 解析分页参数
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    
    res.json({
      data: mockCustomers,
      total: mockCustomers.length,
      stats: mockStats,
      page,
      pageSize
    });
  } catch (error) {
    console.error('提供临时CRM客户数据失败:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
});

// 临时CRMAPI - 所有修改操作都返回成功
router.put('/crm/customers/:id', (req, res) => {
  res.json({ message: '客户更新成功', success: true });
});

router.post('/crm/customers', (req, res) => {
  const newId = Date.now() % 1000;
  res.json({ 
    message: '客户创建成功', 
    success: true,
    id: newId,
    name: req.body.name
  });
});

router.delete('/crm/customers/:id', (req, res) => {
  res.json({ message: '客户删除成功', success: true });
});

// API状态检查
router.get('/status', (req, res) => {
  res.json({ status: 'API服务运行正常' });
});

// 添加数据库诊断API (仅在开发环境可用)
router.get('/diagnose/db', async (req, res) => {
  if (process.env.NODE_ENV === 'production') {
    return res.status(403).json({ message: '此接口仅在开发环境可用' });
  }
  
  try {
    // 检查数据库连接
    await sequelize.authenticate();
    
    // 获取用户数量
    const { User } = require('../models');
    const userCount = await User.count();
    
    // 尝试查询一个用户
    const sampleUser = await User.findOne({
      attributes: ['id', 'username', 'role', 'status', 'createdAt']
    });
    
    // 检查表结构
    const tableInfo = await sequelize.getQueryInterface().describeTable('users');
    
    res.json({
      message: '数据库诊断完成',
      connection: '正常',
      timestamp: new Date().toISOString(),
      statistics: {
        userCount,
        sampleUser: sampleUser ? {
          id: sampleUser.id,
          username: sampleUser.username,
          role: sampleUser.role,
          status: sampleUser.status,
          createdAt: sampleUser.createdAt
        } : null
      },
      tableStructure: {
        users: tableInfo
      }
    });
  } catch (error) {
    res.status(500).json({ 
      message: '数据库诊断失败',
      error: error.message, 
      stack: error.stack
    });
  }
});

// 注册活跃度路由
router.use('/activity', activityRoutes);

module.exports = router; 